package com.bestseller.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.bestseller.dao.ICommonDao;
import com.bestseller.util.GenericClass;

@SuppressWarnings("unchecked")
public class CommonDaoImpl<T> extends HibernateDaoSupport implements ICommonDao<T> {
	//获取父类的泛型类类型
	private Class clazz=GenericClass.getGenericClass(this.getClass());
	
	@Resource(name="sessionFactory")
	public  void setSessionFactoryDI(SessionFactory sessionFactory) {
	    //调用父类的setSessionFactory方法,注入sessionFactory
		super.setSessionFactory(sessionFactory);
	}
	
	@Override
	public void save(T entity) {
		this.getHibernateTemplate().save(entity);
	}

	@Override
	public void update(T entity) {
		this.getHibernateTemplate().update(entity);
	}

	@Override
	public T selectById(Serializable id) {
		if(id==null){
			throw new RuntimeException("你要查找的["+id+"]不能为空");
		}
		return (T) this.getHibernateTemplate().get(clazz, id);
	}

	@Override
	public void deleteByIds(Serializable... ids) {
		if(ids!=null&&ids.length>0){
			for (Serializable id : ids) {
				Object o=selectById(id);
				if(o==null){
					throw new RuntimeException("删除的["+id+"]不存在!");
				}
				this.getHibernateTemplate().delete(o);
			}
		}
	}

	@Override
	public List<T> selectOfCondition(String string,final Object[] param, LinkedHashMap<String, String> orderby) {
		String hql="select o from  "+clazz.getSimpleName()+" o where 1=1 ";
		if(StringUtils.isNotBlank(string)){
			hql+=string;
		}
		String orderbyStr=buildOrderBy(orderby);
		hql+=orderbyStr;
		final String fhql=hql;
		List<T> list=(List<T>) this.getHibernateTemplate().execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = session.createQuery(fhql);
				if(param!=null&&param.length>0){
					for (int i = 0; i < param.length; i++) {
						query.setParameter(i, param[i]);
					}
				}
				return query.list();
			}
		});
		return list;
	}

	private String buildOrderBy(LinkedHashMap<String, String> orderby) {
		StringBuilder sb=new StringBuilder("");
		if(orderby!=null&&orderby.size()>0){
			sb.append("order by ");
			for(Map.Entry<String, String> order:orderby.entrySet()){
				sb.append(order.getKey()+" "+order.getValue()+",");
			}
			sb.deleteCharAt(sb.length()-1);
		}
		return sb.toString();
	}

	
	


}
